package com.ruoyi.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts.replaceAll("/", "-"));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static final String parseStrToStr(final String format, final String date) {

        Date tempDate = dateTime(format, date);

        return new SimpleDateFormat(format).format(tempDate);
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 计算一个月中有多少天
     **/
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    public static long getDatePoorMinutes(Date endDate, Date nowDate) {
        return (endDate.getTime() - nowDate.getTime()) / 1000 / 60;
    }

    public static long getOverTime() throws ParseException {
        long now = System.currentTimeMillis();
        Date date = org.apache.commons.lang3.time.DateUtils.addHours(new Date(), 24);
        long time = date.getTime();

        return time - now;
    }

    /**
     * 省份证的正则表达式^(\d{15}|\d{17}[\dx])$
     *
     * @param id 省份证号
     * @return 生日（yyyy-MM-dd）
     */
    public static String extractYearMonthDayOfIdCard(String id) {
        String year = null;
        String month = null;
        String day = null;
        //正则匹配身份证号是否是正确的，15位或者17位数字+数字/x/X
        if (id.matches("^\\d{15}|\\d{17}[\\dxX]$")) {
            year = id.substring(6, 10);
            month = id.substring(10, 12);
            day = id.substring(12, 14);
        } else {
            System.out.println("身份证号码不匹配！");
            return null;
        }
        return year + "-" + month + "-" + day;
    }

    //获取年龄
    public static int getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            return -1;
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一

            }
        }
        return age;
    }

    //redis 缓存时间点
    public static long getOverTime_24(String endTime) throws ParseException {
        long now = System.currentTimeMillis();
        Date date = org.apache.commons.lang3.time.DateUtils.addHours(dateTime(YYYY_MM_DD, endTime), 24);
        long time = date.getTime();
        return time - now;
    }


    public static String[] getDates(String year, String month) {
        int maxDate = 0;
        Date first = null;
        try {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            first = sdf.parse(year + month);
            cal.setTime(first);
            maxDate = cal.getMaximum(Calendar.DAY_OF_MONTH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String[] dates = new String[maxDate - 1];
        for (int i = 1; i < maxDate; i++) {
            dates[i - 1] = parseDateToStr("yyyy-MM-dd", new Date(first.getTime()));
            first.setDate(first.getDate() + 1);
        }
        return dates;
    }

    /**
     * 功能描述: 指定时间向前/后多少天
     *
     * @param date 时间
     * @param d    天数; 正数时向后；负数时向前
     * @return 向前/后多少天的时间
     */
    public static String getDifferDay(Date date, int d) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, d);
        date = calendar.getTime();
        //DateFormat df = DateFormat.getDateInstance("yyyy-MM-dd");
        String dateString = getFormatDate(date, "yyyy-MM-dd");
        return dateString;
    }

    /**
     * 功能描述: 指定时间转化成指定格式字符串
     *
     * @param date   时间
     * @param format 格式 如：yyyy-MM-dd
     * @return 转换后的时间格式字符串
     */
    public static String getFormatDate(Date date, String format) {
        SimpleDateFormat myFormatter = new SimpleDateFormat(format);
        String formateDate = myFormatter.format(date);
        return formateDate;
    }


    /**
     * @param stime, etime
     * @return java.util.List<java.lang.String>
     * @title 根据开始时间，结束时间获取期间所有日期yyyy-MM-dd
     * 例：开始时间：2019-05-01 结束时间：2019-05-05
     */
    public static List<String> findDates(String stime, String etime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date dBegin = sdf.parse(stime);
        Date dEnd = sdf.parse(etime);

        List<String> allDate = new ArrayList();
        allDate.add(sdf1.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf1.format(calBegin.getTime()));
        }
        return allDate;
    }

    /**
     * 根据开始时间，结束时间获取期间所有日期yyyy-MM-dd
     * 例：开始时间：2019-05-01 结束时间：2019-05-05
     *
     * @param: stime 开始时间
     * @param: etime 结束时间
     * @return: java.util.List<java.util.Date>
     * @author Hush.
     * @date: 2021/11/21 21:36
     */
    public static List<Date> findDateList(String stime, String etime) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dBegin = sdf.parse(stime);
        Date dEnd = sdf.parse(etime);

        List<Date> allDate = new ArrayList();
        allDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(calBegin.getTime());
        }
        return allDate;
    }

    /**
     * 获取当前月第一天
     *
     * @param month
     * @return
     */
    public static String getFirstDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最小天数
        int firstDay = calendar.getActualMinimum(Calendar.DAY_OF_MONTH);
        // 设置日历中月份的最小天数
        calendar.set(Calendar.DAY_OF_MONTH, firstDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String day = sdf.format(calendar.getTime());
        return day;
    }


    /**
     * 获取当前月最后一天
     *
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        // 设置月份
        calendar.set(Calendar.MONTH, month - 1);
        // 获取某月最大天数
        int lastDay = 0;
        //2月的平年瑞年天数
        if (month == 2) {
            lastDay = calendar.getLeastMaximum(Calendar.DAY_OF_MONTH);
        } else {
            lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        // 设置日历中月份的最大天数
        calendar.set(Calendar.DAY_OF_MONTH, lastDay);
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String day = sdf.format(calendar.getTime());
        return day;
    }

    public static int getDayIndex(String date) {
        String day = date.split("-")[2];
        return Integer.parseInt(day);
    }

    /**
     * 通过身份证号码获取出生日期(birthday)、年龄(age)、性别(sex)
     *
     * @param idCardNo 身份证号码
     * @return 返回的出生日期格式：1993-05-07   性别格式：1:男，0:女
     */
    public static Map<String, String> getBirthdayAgeSex(String idCardNo) {
        String birthday = "";
        String age = "";
        String sexCode = "";

        int year = Calendar.getInstance().get(Calendar.YEAR);
        char[] number = idCardNo.toCharArray();
        boolean flag = true;
        if (number.length == 15) {
            for (int x = 0; x < number.length; x++) {
                if (!flag) {
                    return new HashMap<String, String>();
                }
                flag = Character.isDigit(number[x]);
            }
        } else if (number.length == 18) {
            for (int x = 0; x < number.length - 1; x++) {
                if (!flag) {
                    return new HashMap<String, String>();
                }
                flag = Character.isDigit(number[x]);
            }
        }
        if (flag && idCardNo.length() == 15) {
            birthday = "19" + idCardNo.substring(6, 8) + "-"
                    + idCardNo.substring(8, 10) + "-"
                    + idCardNo.substring(10, 12);
            sexCode = Integer.parseInt(idCardNo.substring(idCardNo.length() - 3, idCardNo.length())) % 2 == 0 ? "2" : "1";
            age = (year - Integer.parseInt("19" + idCardNo.substring(6, 8))) + "";
        } else if (flag && idCardNo.length() == 18) {
            birthday = idCardNo.substring(6, 10) + "-"
                    + idCardNo.substring(10, 12) + "-"
                    + idCardNo.substring(12, 14);
            sexCode = Integer.parseInt(idCardNo.substring(idCardNo.length() - 4, idCardNo.length() - 1)) % 2 == 0 ? "2" : "1";
            age = (year - Integer.parseInt(idCardNo.substring(6, 10))) + "";
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("birthday", birthday);
        map.put("age", age);
        map.put("sex", sexCode);
        return map;
    }

    /**
     * 获取当天的最后时间
     *
     * @param date:java.util.Date
     * @return java.lang.String
     * @author Hush.
     * @since 2021/11/21 16:29
     */
    public static Date getTheLastTimeOfTheDay(Date date) throws ParseException {
        if (null == date) {
            date = getNowDate();
        }
        String format = DateFormatUtils.format(date, "yyyy-MM-dd 23:59:59");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return simpleDateFormat.parse(format);
    }


    public static void main(String[] args) {

        int i = (int) (Math.random() * 90) + 10;
        System.out.println(dateTimeNow() + i);

    }
}
